package com.ssn.controller;


import com.ssn.service.impl.BlogServiceImpl;
import com.ssn.service.impl.CommentServiceImpl;
import com.ssn.service.impl.TagServiceImpl;
import com.ssn.service.impl.TypeServiceImpl;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;

@Controller
public class IndexController {

    @Resource
    private BlogServiceImpl blogService;
    @Resource
    private TypeServiceImpl typeService;
    @Resource
    private TagServiceImpl tagService;
    @Resource
    private CommentServiceImpl commentService;



    @GetMapping("/")
    public String index(@PageableDefault(size = 10,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                        Model model){
        model.addAttribute("page",blogService.listBlogPublished(pageable));
        model.addAttribute("types",typeService.listTypeTop(6));
        model.addAttribute("tags",tagService.listTagTop(10));
        model.addAttribute("recommendBlogs",blogService.listRecommendBlogTop(8));
        return "index";
    }


    @GetMapping("fragment")
    public String fragment(){

        return "fragment";
    }

    @GetMapping("admin/login")
    public String adminLogin(){

        return "admin/login";
    }

    @PostMapping("/search")
    public String searchPage(String search,@PageableDefault(size = 10,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                             Model model){
        model.addAttribute("page",blogService.findBlogBySearch( "%" +  search + "%",pageable));
        model.addAttribute("search",search);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model){
        model.addAttribute("blog",blogService.getAndConvert(id));
        model.addAttribute("comments", commentService.lisTCommentByBlogId(id));
        return "blog";
    }

    @GetMapping("/footer/newblogs")
    public String newBlog(Model model){
        model.addAttribute("newblogs", blogService.listRecommendBlogTop(3));
        return "fragment :: newBlogList";
    }




}
